<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品设计思维分析系统</title>
    <style>
        :root {
            --primary: #3b82f6;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
            --gray: #64748b;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            line-height: 1.6;
            color: #1f2937;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        header { text-align: center; margin-bottom: 30px; }
        h1 { color: var(--primary); font-size: 28px; margin-bottom: 10px; }
        .subtitle { color: var(--gray); font-size: 18px; }

        /* 上传区域 */
        .upload-area {
            border: 2px dashed #cbd5e1;
            border-radius: 12px;
            padding: 40px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background-color: #f8fafc;
            margin-bottom: 30px;
        }
        .upload-area:hover { border-color: var(--primary); background-color: #eff6ff; }
        .upload-icon { font-size: 48px; color: var(--primary); margin-bottom: 15px; }
        .upload-text h2 { color: var(--primary); margin-bottom: 10px; }
        .upload-text p { color: var(--gray); margin-bottom: 20px; }

        /* 按钮样式 */
        .btn {
            background-color: var(--primary);
            color: white;
            border: none;
            padding: 12px 24px;
            font-size: 16px;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s;
            margin: 0 5px;
        }
        .btn:hover { background-color: #2563eb; }
        .btn-success { background-color: var(--success); }
        .btn-success:hover { background-color: #059669; }

        /* 处理中状态 */
        .processing {
            text-align: center;
            padding: 30px 0;
            display: none;
        }
        .spinner {
            border: 4px solid rgba(59, 130, 246, 0.2);
            border-top: 4px solid var(--primary);
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        #upload-progress { color: var(--primary); margin-top: 10px; }

        /* 结果区域 */
        .results {
            margin-top: 30px;
            padding: 20px;
            border-radius: 12px;
            background-color: white;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            display: none;
        }
        .section-title {
            color: var(--primary);
            font-size: 22px;
            margin: 25px 0 15px;
            padding-bottom: 8px;
            border-bottom: 1px solid #e2e8f0;
        }
        .card {
            background-color: #f8fafc;
            border-radius: 8px;
            padding: 18px;
            margin-bottom: 15px;
            border-left: 4px solid var(--primary);
        }
        .card-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 12px;
            font-weight: 600;
        }
        .detail-item { margin: 8px 0; }
        .detail-item strong {
            color: var(--gray);
            width: 120px;
            display: inline-block;
        }
        .strategy-list { margin-left: 20px; }
        .strategy-item { margin: 10px 0; }

        /* 标签页 */
        .tab-container { margin: 10px 0; border-bottom: 1px solid #e2e8f0; }
        .tab {
            display: inline-block;
            padding: 6px 12px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            margin-right: 5px;
        }
        .tab.active { border-bottom-color: var(--primary); color: var(--primary); font-weight: 500; }
        .tab-content { padding: 10px 0; display: none; }
        .tab-content.active { display: block; }

        /* 历史记录链接 */
        .history-link {
            text-align: center;
            margin: 20px 0;
        }
        .history-link a { color: var(--primary); text-decoration: none; }
        .history-link a:hover { text-decoration: underline; }
    </style>
</head>
<body>
    <header>
        <h1>🔍 产品设计思维分析系统</h1>
        <p class="subtitle">剖析优秀产品设计思路，提取可复用的设计策略</p>
    </header>

    <!-- 上传区域 -->
    <div class="upload-area" id="drop-area">
        <div class="upload-icon">
            <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" fill="currentColor" viewBox="0 0 16 16">
                <path d="M13.5 2a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-.5.5H13v2h-1V6.5a.5.5 0 0 1-.5-.5V6H8v.5a.5.5 0 0 1-.5.5V7H6v-.5a.5.5 0 0 1-.5-.5V6H3v.5a.5.5 0 0 1-.5.5V7H1V6.5a.5.5 0 0 1 .5-.5h2a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-.5.5H3v2h10v-2h1V4h-1v-.5a.5.5 0 0 1 .5-.5h2a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-.5.5h-1v2h-1v-2.5a.5.5 0 0 1 .5-.5h1v-1z"/>
            </svg>
        </div>
        <div class="upload-text">
            <h2>上传产品操作视频</h2>
            <p>支持 MP4/AVI/MOV/MKV/FLV/WMV 格式 | 最大支持500MB<br>
               建议：上传3-5分钟核心功能操作片段，分析更精准</p>
            <form id="upload-form" enctype="multipart/form-data">
                <input type="file" name="video" id="video-file" accept="video/mp4,video/avi,video/mov,video/mkv,video/flv,video/wmv" style="display: none;">
                <button type="button" class="btn" id="browse-btn">选择视频文件</button>
            </form>
        </div>
    </div>

    <!-- 处理中状态 -->
    <div class="processing" id="processing">
        <div class="spinner"></div>
        <h3>正在分析产品设计思维...</h3>
        <p>步骤1/3：提取功能帧 → 步骤2/3：AI分析设计逻辑 → 步骤3/3：生成可复用策略</p>
        <div id="upload-progress"></div>
    </div>

    <!-- 结果区域 -->
    <div class="results" id="results">
        <!-- 导出按钮 -->
        <div style="text-align: center; margin-bottom: 20px;">
            <button class="btn btn-success" id="exportBtn" style="display: none;">导出分析报告（Excel）</button>
        </div>

        <!-- 设计思维框架 -->
        <h2 class="section-title">一、设计思维框架</h2>
        <div class="card">
            <div class="detail-item"><strong>产品定位：</strong><span id="product-positioning">未观察到</span></div>
            <div class="detail-item"><strong>目标用户：</strong><span id="target-users">未观察到</span></div>
            <div class="detail-item"><strong>问题拆解：</strong><span id="problem-decomposition">未观察到</span></div>
            <div class="detail-item"><strong>场景优先级：</strong><span id="scene-priority">未观察到</span></div>
        </div>

        <!-- 具体设计内容 -->
        <h2 class="section-title">二、具体设计内容</h2>
        <div class="card">
            <div class="detail-item"><strong>模块结构：</strong><span id="module-structure">未观察到</span></div>
            <div class="detail-item"><strong>交互流程：</strong><span id="interaction-flow">未观察到</span></div>
            <div class="detail-item"><strong>数据流转：</strong><span id="data-flow">未观察到</span></div>
        </div>

        <!-- 可复用设计策略 -->
        <h2 class="section-title">三、可复用设计策略</h2>
        <div class="card" id="strategy-container">
            <div id="strategy-default">未观察到可复用策略</div>
            <ul class="strategy-list" id="strategy-list" style="display: none;"></ul>
        </div>

        <!-- 核心学习点 -->
        <h2 class="section-title">四、核心学习点</h2>
        <div class="card">
            <span id="key-lessons">未总结出核心学习点</span>
        </div>
    </div>

    <!-- 历史记录链接 -->
    <div class="history-link">
        <a href="/history">查看历史分析记录 →</a>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // DOM元素
            const dropArea = document.getElementById('drop-area');
            const fileInput = document.getElementById('video-file');
            const browseBtn = document.getElementById('browse-btn');
            const processing = document.getElementById('processing');
            const results = document.getElementById('results');
            const uploadProgress = document.getElementById('upload-progress');
            const exportBtn = document.getElementById('exportBtn');
            let currentAnalysisId = null;

            // 预加载历史结果（如果有）
            const preloadData = window.preloadData || null;
            if (preloadData) {
                currentAnalysisId = preloadData.analysis_id;
                renderResults(preloadData);
                processing.style.display = 'none';
                results.style.display = 'block';
                exportBtn.style.display = 'inline-block';
            }

            // 拖放逻辑：正确获取CSS变量
            const primaryColor = getComputedStyle(document.documentElement)
                .getPropertyValue('--primary')
                .trim();

            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropArea.addEventListener(eventName, preventDefaults, false);
            });
            function preventDefaults(e) { e.preventDefault(); e.stopPropagation(); }
            ['dragenter', 'dragover'].forEach(e => dropArea.addEventListener(e, highlight, false));
            ['dragleave', 'drop'].forEach(e => dropArea.addEventListener(e, unhighlight, false));
            function highlight() {
                dropArea.style.borderColor = primaryColor;
                dropArea.style.backgroundColor = '#eff6ff';
            }
            function unhighlight() {
                dropArea.style.borderColor = '#cbd5e1';
                dropArea.style.backgroundColor = '#f8fafc';
            }

            // 处理拖放文件
            dropArea.addEventListener('drop', handleDrop, false);
            function handleDrop(e) {
                const files = e.dataTransfer.files;
                if (files.length) {
                    fileInput.files = files;
                    submitForm();
                }
            }

            // 点击选择文件
            browseBtn.addEventListener('click', () => fileInput.click());
            fileInput.addEventListener('change', () => fileInput.files.length && submitForm());

            // 提交表单（支持大文件上传进度）
            function submitForm() {
                const file = fileInput.files[0];
                const validTypes = ['video/mp4', 'video/avi', 'video/mov', 'video/mkv', 'video/flv', 'video/wmv'];

                // 类型校验
                if (!validTypes.includes(file.type) && !file.name.match(/\.(mp4|avi|mov|mkv|flv|wmv)$/i)) {
                    alert('请选择支持的视频格式：MP4/AVI/MOV/MKV/FLV/WMV');
                    return;
                }

                // 大小校验（500MB）
                const maxSize = 500 * 1024 * 1024;
                const fileSizeMB = file.size / 1024 / 1024;
                if (file.size > maxSize) {
                    alert(`视频过大（${fileSizeMB.toFixed(2)}MB），最大支持500MB\n建议：\n1. 用HandBrake压缩码率\n2. 截取3-5分钟核心片段`);
                    return;
                }

                // 大文件确认（>200MB）
                if (fileSizeMB > 200 && !confirm(`视频${fileSizeMB.toFixed(2)}MB，上传+分析需5-10分钟，是否继续？`)) {
                    return;
                }

                // 显示处理状态
                processing.style.display = 'block';
                results.style.display = 'none';

                // 构建FormData
                const formData = new FormData();
                formData.append('video', file);

                // 上传+分析（带进度）
                fetch('/analyze_function', {
                    method: 'POST',
                    body: formData,
                    timeout: 300000, // 5分钟超时
                    onUploadProgress: (e) => {
                        if (e.lengthComputable) {
                            const percent = Math.round((e.loaded / e.total) * 100);
                            uploadProgress.textContent = `上传进度：${percent}%`;
                        }
                    }
                })
                .then(res => {
                    if (!res.ok) throw new Error(`HTTP错误：${res.status}`);
                    return res.json();
                })
                .then(data => {
                    if (data.error) throw new Error(data.error);
                    currentAnalysisId = data.analysis_id;
                    renderResults(data);
                    processing.style.display = 'none';
                    results.style.display = 'block';
                    exportBtn.style.display = 'inline-block';
                })
                .catch(err => {
                    processing.style.display = 'none';
                    alert(`分析失败：${err.message}`);
                    console.error(err);
                });
            }

            // 渲染分析结果
            function renderResults(data) {
                // 设计思维框架
                document.getElementById('product-positioning').textContent = data.design_thinking_framework?.product_positioning || '未观察到';
                document.getElementById('target-users').textContent = data.design_thinking_framework?.target_users || '未观察到';
                document.getElementById('problem-decomposition').textContent = data.design_thinking_framework?.user_problem_decomposition || '未观察到';
                document.getElementById('scene-priority').textContent = data.design_thinking_framework?.scene_priority_logic || '未观察到';

                // 具体设计内容
                document.getElementById('module-structure').textContent = data.concrete_design_content?.function_module_structure || '未观察到';
                document.getElementById('interaction-flow').textContent = data.concrete_design_content?.interaction_design_flow || '未观察到';
                document.getElementById('data-flow').textContent = data.concrete_design_content?.data_flow_design || '未观察到';

                // 可复用策略
                const strategies = data.reusable_design_strategies || [];
                const strategyDefault = document.getElementById('strategy-default');
                const strategyList = document.getElementById('strategy-list');
                if (strategies.length && strategies[0].strategy_name !== '未观察到') {
                    strategyDefault.style.display = 'none';
                    strategyList.style.display = 'block';
                    strategyList.innerHTML = '';
                    strategies.forEach((s, idx) => {
                        const li = document.createElement('li');
                        li.className = 'strategy-item';
                        li.innerHTML = `
                            <strong>${idx+1}. ${s.strategy_name}</strong><br>
                            具体内容：${s.concrete_content}<br>
                            适用场景：${s.applicable_scenario}
                        `;
                        strategyList.appendChild(li);
                    });
                } else {
                    strategyDefault.style.display = 'block';
                    strategyList.style.display = 'none';
                }

                // 核心学习点
                document.getElementById('key-lessons').textContent = data.key_lessons || '未总结出核心学习点';
            }

            // 导出报告
            exportBtn.addEventListener('click', () => {
                if (currentAnalysisId) {
                    window.location.href = `/export_analysis/${currentAnalysisId}`;
                } else {
                    alert('未获取到分析ID，无法导出');
                }
            });
        });
    </script>
</body>
</html>